package com.bee.beemanage.system.common.utils;

import javax.servlet.http.HttpServletRequest;

/**
 * ip工具类
 */
public class IpUtil {
    private static final String UNKNOWN = "unknown";
    private static final String HEADER_PROXY = "Proxy-Client-IP";

    /**
     * 获取请求的IP地址(前端经过nginx代理了,所以服务记录的是nginx的地址，而不是真实地址,需要在nginx配置如下
     * location ~ ^/admin/ {
     * proxy_set_header    Proxy-Client-IP           $remote_addr;
     * proxy_pass http://121.36.100.161:8090; #后端地址
     * }
     * Proxy-Client-IP 与此工具类的 Proxy-Client-IP 对应从而获得真实的ip地址
     * @param request 请求体
     * @return IP地址
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader(HEADER_PROXY);
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}